package com.xiaotu.emailspringboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Author xiaotu
 * @Description //TODO
 * @Date 2022/3/21 11:43
 * @ClassName SendmailService
 * @Version 1.0
 **/
@Service
public class SendmailService {
    @Value("${spring.mail.username}")
    private String username;
    @Autowired
    private JavaMailSender sender;

    public String sendEmailMethod(String to,String subject,String text,String filePath,String rscPath,String rscId){
        MimeMessage mimeMessage = sender.createMimeMessage();
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text,true);
            helper.setFrom(username);
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            FileSystemResource rscPathResource = new FileSystemResource(rscPath);
            helper.addInline(rscId, rscPathResource);
            String filename = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(filename, fileSystemResource);
            sender.send(mimeMessage);
            return "发送成功";
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new RuntimeException("发送失败");

        }
    }

    public String  sendEmailTemplate(String to, String subject, String filePath, String flower) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setFrom(username);
            //设置发送附件
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            String filename = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(filename, fileSystemResource);
            //设置发送模板
            helper.setText(flower, true);
            sender.send(mimeMessage);
            return "发送成功";
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new RuntimeException("发送失败");

        }
    }
}
